package io.gitee.hchaojie.day08.thread;

public class TestDeadlock2 {
    public static void main(String[] args) {
        Object[] locks = new Object[5];

        for (int i = 0; i < 5; i++) {
            locks[i] = new Object();        // 模拟五根筷子
        }

        for (int i = 0; i < 5; i++) {
            final int left = (i == 4 ? 0 : i);
            final int right = (i == 4) ? 4 : (i + 1) % 5;

            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    synchronized (locks[left]) {
                        System.out.println(Thread.currentThread().getName()
                                + "拿到了左边的筷子。。。" + left);

                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                        synchronized (locks[right]) {
                            System.out.println(Thread.currentThread().getName() +
                                    "拿到了右边的筷子。。。" + right);
                        }
                    }
                }
            });

            thread.start();
        }

    }
}
